from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, DateTime, func
from sqlalchemy.ext.declarative import AbstractConcreteBase
from sqlalchemy.orm import relationship

from apps.utils.database import Base


class PublcModel(AbstractConcreteBase, Base):
    id = Column(Integer, primary_key=True, index=True)
    createtime = Column(DateTime, server_default=func.now(), comment='创建时间')
    updatetime = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment='修改时间')


class User(PublcModel):
    __tablename__ = "users"
    email = Column(String, index=True,  comment='邮箱')
    hashed_password = Column(String, nullable=False, comment='密文密码')
    is_active = Column(Boolean, default=True, comment='账号是否激活，默认是激活')
    nickname = Column(String, index=True, default='游客', comment='昵称')
    contact_number = Column(String, nullable=False, unique=True, comment='联系电话，用来做登录账号')
    last_login_date = Column(DateTime, comment='上次登录时间')
    last_login_ip = Column(String, comment='上次ip')
    photo = Column(String, comment='头像')
    createtime = Column(DateTime, server_default=func.now(), comment='创建时间')
    updatetime = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment='修改时间')
    is_delete = Column(Boolean, default=False, comment='是否删除')
    role_id = Column(Integer, comment='角色id')

    items = relationship("Item", back_populates="owner")

    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}


class Role(PublcModel):
    __tablename__ = "role"
    role_name = Column(String, comment='角色名称')

    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}


class Item(Base):
    __tablename__ = "items"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    description = Column(String, index=True)
    owner_id = Column(Integer, ForeignKey("users.id"))

    owner = relationship("User", back_populates="items")
